package com.echo.register.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.echo.register.common.exception.RegisterException;
import com.echo.register.common.result.ResultCodeEnum;
import com.echo.register.oss.service.FileService;
import com.echo.register.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName: FileServiceImpl
 * @Package: com.echo.register.oss.impl
 * @Description:
 * @Author 谢同学
 * @Create 2023/12/31 18:35
 * @Version 1.0
 */
@Component
public class FileServiceImpl implements FileService {

    /**
     * 上传文件到阿里云
     *
     * @param file 文件上传类
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        // 校验文件是否为空
        if (file == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        try {
            // 创建客户端
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取原始文件名称
            String fileName = file.getOriginalFilename();
            String substring = null;
            if (fileName != null) {
                substring = fileName.substring(fileName.lastIndexOf("."));
            }
            // 生成随机唯一值，使用uuid，添加到文件名称里面
            fileName = UUID.randomUUID().toString().replaceAll("-", "") + substring;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;

            // 调用方法实现上传
            oss.putObject(ConstantOssPropertiesUtils.BUCKET, fileName, file.getInputStream());
            // 关闭客户端
            oss.shutdown();
            // 返回全路径
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
